import utils from "@/utils/utils.js";

export default {
  //获取定位
  getLocation(context) {
    return new Promise((resolve, reject) => {
      mapSelect()
      function mapSelect(params) {
        uni.getLocation({
          type: 'gcj02',
          success: res => {
            let location = {
              latitude: res.latitude,
              longitude: res.longitude
            }
            //console.log("uniapp自带获取", location)
            //uni.setStorageSync('location', location)
            resolve(location)
          },
          fail: async (e) => {
            this.openSetting("userLocation")
          }
        })
      }
    })
  },

  //登录
  login(context, univerifyStyle) {
    return new Promise((resolve, reject) => {
      let obj = {
        provider: context ? context : 'weixin',
        success: (res) => {
          if (res.code) {
            resolve(res.code)
          } else {
            resolve(res.authResult)
          }
        },
        fail: err => {
          // uni.$uv.toast(err)
          reject(err.errMsg)
        }
      }
      // #ifdef APP-PLUS
      obj.onlyAuthorize = true
      if (univerifyStyle) obj.univerifyStyle = univerifyStyle
      // #endif
      uni.login(obj)
    })
  },

  //上传图片
  chooseImage(context) {
    return new Promise((resolve, reject) => {
      uni.chooseImage({
        count: context ? context : 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: res => {
          resolve(res.tempFilePaths)
        }
      })
    })
  },

  //上传视频
  chooseVideo(context) {
    return new Promise((resolve, reject) => {
      uni.chooseVideo({
        count: 1,
        sourceType: ['camera', 'album'],
        compressed: false,
        success: res => {
          if (res.duration > 15) {
            return uni.$uv.toast("上传的视频时长不超过15s")
          }
          resolve(res.tempFilePath)
        }
      })
    })
  },

  //本地图片转成base64
  transBase64(context) {
    return new Promise((resolve, reject) => {
      // #ifdef H5
      uni.request({
        url: context,
        method: 'GET',
        responseType: 'arraybuffer',
        success: res => {
          let base64 = uni.arrayBufferToBase64(res.data); //把arraybuffer转成base64
          base64 = 'data:image/png;base64,' + base64;
          resolve(base64)
        }
      })
      // #endif

      // #ifdef MP-WEIXIN
      uni.getFileSystemManager().readFile({
        filePath: context, //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => { //成功的回调
          let path = 'data:image/png;base64,' + res.data
          resolve(path)
        }
      })
      // #endif

      // #ifdef APP-PLUS
      plus.io.resolveLocalFileSystemURL(url, (entry) => {
        entry.file((file) => {
          let fileReader = new plus.io.FileReader();
          if (file.size > 450 * 1024) {
            return uni.showToast({
              title: '图片大小不能超过450k',
              icon: 'none'
            })
          }
          fileReader.onloadend = (e) => {
            resolve(e.target.result)
          };
          fileReader.readAsDataURL(file);
        })
      })
      // #endif
    })
  },

  //打开地图，选择位置
  chooseLocation(context) {
    return new Promise((resolve, reject) => {
      uni.chooseLocation({
        success: (res) => {
          resolve(res)
        },
        fail: (res) => {
          reject(res.errMsg)
        }
      });
    })
  },

  //获取服务供应商
  getProvider(service) {
    return new Promise((resolve, reject) => {
      uni.getProvider({
        service,
        success: (res) => {
          resolve(res.provider)
        },
        fail: (res) => {
          reject(res.errMsg)
        }
      });
    })
  },

  //预登录 用于App手机号一键登录
  preLogin(provider) {
    return new Promise((resolve, reject) => {
      uni.preLogin({
        provider,
        success(res) {
          console.log('预登录成功', res);
          resolve(true)
        },
        fail(err) {
          console.log("号称", err.errMsg)
          reject(err.errMsg)
        }
      })
    })
  },

  //获取图片信息
  getImageInfo(context) {
    return new Promise((resolve, reject) => {
      uni.getImageInfo({
        src: context,
        success: function(image) {
          resolve(image)
        }
      });
    })
  },
  //把网络图片改成本地图片
  getNetworkImage(url) {
    return new Promise((resolve, reject) => {
      uni.downloadFile({
        url,
        success: (e) => {
          resolve(e)
        }
      })
    })
  },

  //预览图片
  previewImage(imgcont, index) {
    uni.previewImage({
      current: index,
      urls: imgcont,//['你的图片地址']
      indicator: "number",
      loop: true,
    });
  },

  //系统信息
  getSystemInfo(url) {
    return new Promise((resolve, reject) => {
      uni.getSystemInfo({
        success: function(res) {
          resolve(res)
        }
      });
    })
  },

  //获取cid
  getCidAsync() {
    return new Promise((resolve, reject) => {
      // 获取客户端推送信息
      plus.push.getClientInfoAsync(function(clientInfo) {
        // 获取CID
        var cid = clientInfo.clientid;
        // 调用resolve方法返回CID
        resolve(cid);
      }, function(error) {
        // 获取CID失败，调用reject方法返回错误信息
        reject(error);
      });
    })
  },

  //扫码
  scanCode() {
    return new Promise((resolve, reject) => {
      uni.scanCode({
        success: (res) => {
          resolve(res)
        },
        // 失败回调
        fail: (res) => {
          console.log('调用失败!')
        }
      });
    })
  },

  //判断当前环境
  getCurrentEnvironment(context) {
    return new Promise((resolve, reject) => {
      uni.getSystemInfo({
        success: function(res) {
          const platform = res.platform.toLowerCase();
          if (platform === 'devtools') {
            resolve('web');
          } else if (platform === 'ios' || platform === 'android') {
            resolve('app');
          } else if (platform === 'wechat') {
            resolve('wechat');
          } else {
            reject('无法确定当前环境');
          }
        },
        fail: function(error) {
          reject(error);
        }
      })
    });
  },


  //打电话
  makePhoneCall(context) {
    return new Promise((resolve, reject) => {
      uni.makePhoneCall({
        // 手机号
        phoneNumber: context,
        // 成功回调
        success: (res) => {
          console.log('调用成功!')
        },
        // 失败回调
        fail: (res) => {
          console.log('调用失败!')
        }
      });
    })
  },

  //打开地址
  openLocation(context) {
    return new Promise((resolve, reject) => {
      uni.openLocation({
        latitude: Number(context.lat ? context.lat : context.latitude),
        longitude: Number(context.lng ? context.lng : context.longitude),
        scale: 15,
        name: context.name
      });
    })
  },

  //复制粘贴
  setClipboardData(context, showToastText) {
    return new Promise((resolve, reject) => {
      uni.setClipboardData({
        data: context.toString(),
        success: () => {
          uni.showToast({
            title: showToastText ? showToastText : '复制成功',
            duration: 1500,
            icon: 'success'
          });
        }
      });
    })
  },

  //拍摄视频
  chooseVideo() {
    return new Promise((resolve, reject) => {
      uni.chooseVideo({
        sourceType: ['camera', 'album'],
        success: (res) => {
          resolve(res.tempFilePath)
        }
      });
    })
  },

  //获取视频时长
  getVideoInfo(src) {
    return new Promise((resolve, reject) => {
      uni.getVideoInfo({
        src,
        success: (res) => {
          resolve(res)
        }
      });
    })
  },

  //下载文件资源到本地
  downloadFile(imageUrl) {
    return new Promise((resolve, reject) => {
      uni.downloadFile({
        url: imageUrl,
        // timeout: 30000, 超时时间
        success: async (res) => {
          const { statusCode, tempFilePath } = res;
          if (statusCode === 200) {
            console.log("下载文件成功");
            resolve(tempFilePath)
          } else {
            uni.showToast({
              title: "下载文件失败",
            });
          }
        },
      });
    })
  },

  //保存图片
  saveImageToPhotosAlbum(filePath, fileName) {
    return new Promise((resolve, reject) => {
      // #ifdef H5
      // 创建a标签，用于跳转至下载链接
      let blobURL = filePath;
      let fileUrlName = fileName ? fileName : "不好吃";
      const tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = blobURL;
      tempLink.setAttribute("download", decodeURI(fileUrlName));
      // 兼容：某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === "undefined") {
        tempLink.setAttribute("target", "_blank");
      }
      // 挂载a标签
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL);
      // #endif

      // #ifndef H5
      uni.saveImageToPhotosAlbum({
        filePath,
        success: function() {
          uni.showToast({
            title: '保存成功',
            duration: 1500,
            icon: 'success'
          });
        }
      });
      // #endif
    })
  },

  //从底部向上弹出操作菜单
  showActionSheet(itemList) {
    return new Promise((resolve, reject) => {
      uni.showActionSheet({
        itemList,
        success: (res) => {
          resolve(res.tapIndex)
        },
        fail: (res) => {
          console.log("嘻嘻", res.errMsg);
        }
      });
    })
  },

  //授权
  getSetting(type) {
    return new Promise((resolve, reject) => {
      uni.getSetting({
        success(res) {
          console.log("已经授权的权限", res);
          //address invoice invoiceTitle record userInfo
          let bool = false
          if (res.authSetting.hasOwnProperty(`scope.${type}`)) {
            bool = res.authSetting[`scope.${type}`]
          }
          resolve(bool)
        }
      });
    })
  },

  //发起授权请求
  authorize(type) {
    return new Promise((resolve, reject) => {
      let scope = `scope.${type}`
      uni.authorize({
        scope,
        success(res) {
          resolve(true)
        },
        fail(err) {
          console.log("授权失败", err);
          this.openSetting(type)
        }
      });
    })
  },

  getScopeFormat(type) {
    let name
    switch (type) {
      case "record":
        name = "录音"
        break;
      case "userInfo":
        name = "用户信息"
        break;
      case "userLocation":
        name = "地理位置"
        break;
      case "userLocationBackground":
        name = "后台定位"
        break;
      case "address":
        name = "通信地址"
        break;
      case "writePhotosAlbum":
        name = "保存到相册"
        break;
      case "camera":
        name = "摄像头"
        break;
      case "invoice":
        name = "获取发票"
        break;
      case "invoiceTitle":
        name = "发票抬头"
        break;
      case "werun":
        name = "微信运动步数"
        break;
      default:
        break;
    }
    return name
  },

  async openSetting(type) {
    let name = this.getScopeFormat(type)
    let resp = await utils.showModal({ title: `是否允许授权${name}功能？`, content: `需要获取您的${name}功能，请确认授权，否则${name}功能将无法使用` })
    if (!resp) return

    return new Promise((resolve, reject) => {
      uni.openSetting({
        success: (data) => {
          // 如果用户授权了地理信息在，则提示授权成功
          if (data.authSetting[`scope.${type}`]) {
            utils.showToast("授权成功", 1)
            resolve(true)
          } else {
            utils.showToast("授权失败")
            resolve(false)
          }
        },
        fail: () => {
          utils.showToast("调用授权窗口失败")
        },
      })
    })
  },

  //小程序通知模板
  requestSubscribeMessage(id) {
    // #ifdef MP-WEIXIN 
    return new Promise((resolve, reject) => {
      uni.requestSubscribeMessage({
        tmplIds: [id],
        success: (res) => {
          //resolve(res[id]) == "accept" ? true : false;
          if (res[id] == "accept") {
            resolve(true)
          } else if (res[id] === 'reject') {
            // 用户历史操作有设置了拒绝 or 关闭了订阅消息的主（总）开关，导致无法推送
            // console.log(res, '0 拒绝 or 关闭了订阅消息的主（总）开关---');
            utils.showToast("订阅消息尚未开启，请前往小程序右上角更多-设置-订阅消息中开启以方便及时接收消息通知")
          } else {
            utils.showToast("授权订阅消息有误", 1)
          }
        },
        fail: (err) => {
          console.log("订阅消息 失败 ", err);
          // 20004:用户关闭了主开关，无法进行订阅,引导开启
          if (err.errCode == 20004) {
            // console.log(res, 'fail:用户关闭了主开关，无法进行订阅,引导开启---');
            return guideOpenSubscribeMessage()
          }
        }
      });
    })
    // #endif
  },

  //上传文件
  chooseFile(context) {
    return new Promise((resolve, reject) => {
      //#ifdef H5
      uni.chooseFile({
        count: !isNaN(context) ? context : 1, //默认100
        type: 'all',
        success: res => {
          console.log("上传文件", res)
          let list = []
          for (let index = 0; index < res.tempFilePaths.length; index++) {
            const element = res.tempFilePaths[index];
            list.push({
              name: res.tempFiles[index].name,
              path: element,
            })
          }
          resolve(list)
        }
      });
      //#endif

      //#ifdef MP-WEIXIN
      wx.chooseMessageFile({ // 使用微信的方法进入聊天界面选择你之前接受过的文件
        count: !isNaN(context) ? context : 1, //默认100
        type: 'file', // 所选的文件的类型，其它属性可以看官方文档
        success: res => {
          resolve(res.tempFiles)
        },
        fail(error) {
          console.log("选择文件失败", error)
          // uni.$u.toast(error)
        }
      })
      //#endif

    })
  },


  //预览文件
  async openDocument(filePath) {
    let url = await this.downloadFile(filePath)
    uni.openDocument({
      filePath: url,
      showMenu: true,
      success: function(res) {
        console.log('打开文档成功');
      },
      fail: function(res) {
        console.log('打开文档失败', res);
      }
    });
  },

  //下载文件
  async saveFile(filePath) {
    let url = await this.downloadFile(filePath)
    return new Promise((resolve, reject) => {
      uni.saveFile({
        tempFilePath: url,
        success: function(res) {
          //保存路径res.savedFilePath
          console.log('下载文件成功', res);
          uni.showToast({
            icon: 'success',
            mask: true,
            title: '文件已保存',
            duration: 1500,
          });
          resolve(res.savedFilePath)
        },
        fail: function(res) {
          console.log('下载文件失败', res);
          reject(res)
        }
      });
    })
  }
}



















